import { useState, useEffect } from 'react';
import {
  Form,
  Input,
  DatePicker,
  Select,
  Button,
  Space,
  Upload,
  message,
  Row,
  Col,
  Divider,
  InputNumber,
  Card
} from 'antd';
import {
  PlusOutlined,
  SaveOutlined,
  CloseOutlined,
  MinusCircleOutlined
} from '@ant-design/icons';
import useDishesStore from '../../store/dishes/useDishesStore';
import dayjs from 'dayjs';

const { TextArea } = Input;
const { Option } = Select;

const categories = ['IPA', 'Stout', 'Wheat', 'Belgian', 'Pale Ale', 'Lager', 'Porter', 'Sour'];

const DishForm = ({ dish, onSuccess, onCancel }) => {
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState([]);
  const [loading, setLoading] = useState(false);
  const { createDish, updateDish } = useDishesStore();

  useEffect(() => {
    if (dish) {
      form.setFieldsValue({
        name: dish.name,
        category: dish.category,
        variants: dish.variants,
        launchTime: dayjs(dish.launchTime),
      });

      if (dish.images && dish.images.length > 0) {
        const images = dish.images.map((url, index) => ({
          uid: `-${index}`,
          name: `image-${index}`,
          status: 'done',
          url,
        }));
        setFileList(images);
      }
    } else {
      form.setFieldsValue({
        variants: [{ size: '330ml', price: 0, discount: 100 }]
      });
    }
  }, [dish, form]);

  const handleUploadChange = ({ fileList: newFileList }) => {
    setFileList(newFileList);
  };

  const beforeUpload = (file) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件！');
      return false;
    }
    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isLt5M) {
      message.error('图片大小不能超过 5MB！');
      return false;
    }
    return false;
  };

  const customUpload = ({ file, onSuccess: uploadSuccess }) => {
    setTimeout(() => {
      uploadSuccess('ok');
    }, 0);
  };

  const handleSubmit = async (values) => {
    setLoading(true);
    try {
      const formData = {
        ...values,
        launchTime: values.launchTime.format('YYYY-MM-DD HH:mm:ss'),
        images: fileList.map(file => file.url || (file.originFileObj ? URL.createObjectURL(file.originFileObj) : null)).filter(Boolean)
      };

      if (dish) {
        await updateDish(dish.id, formData);
        message.success('菜品更新成功');
      } else {
        await createDish(formData);
        message.success('菜品创建成功');
      }
      
      onSuccess?.();
    } catch {
      message.error(dish ? '更新失败' : '创建失败');
    } finally {
      setLoading(false);
    }
  };

  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传图片</div>
    </div>
  );

  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={handleSubmit}
      autoComplete="off"
    >
      <Row gutter={16}>
        <Col span={12}>
          <Form.Item
            label="菜品名称"
            name="name"
            rules={[
              { required: true, message: '请输入菜品名称' },
              { max: 50, message: '菜品名称最多50个字符' }
            ]}
          >
            <Input placeholder="请输入菜品名称" />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            label="菜品分类"
            name="category"
            rules={[{ required: true, message: '请选择菜品分类' }]}
          >
            <Select placeholder="请选择菜品分类">
              {categories.map(cat => (
                <Option key={cat} value={cat}>{cat}</Option>
              ))}
            </Select>
          </Form.Item>
        </Col>
      </Row>

      <Form.Item
        label="上线时间"
        name="launchTime"
        rules={[{ required: true, message: '请选择上线时间' }]}
      >
        <DatePicker
          showTime
          format="YYYY-MM-DD HH:mm"
          style={{ width: '100%' }}
          placeholder="选择上线时间"
        />
      </Form.Item>

      <Divider>规格与价格</Divider>

      <Form.List name="variants">
        {(fields, { add, remove }) => (
          <>
            {fields.map(({ key, name, ...restField }) => (
              <Card key={key} size="small" style={{ marginBottom: 16 }}>
                <Row gutter={16}>
                  <Col span={8}>
                    <Form.Item
                      {...restField}
                      label="容量"
                      name={[name, 'size']}
                      rules={[{ required: true, message: '请输入容量' }]}
                    >
                      <Input placeholder="如: 330ml" />
                    </Form.Item>
                  </Col>
                  <Col span={7}>
                    <Form.Item
                      {...restField}
                      label="原价 (¥)"
                      name={[name, 'price']}
                      rules={[{ required: true, message: '请输入原价' }]}
                    >
                      <InputNumber
                        min={0}
                        precision={2}
                        style={{ width: '100%' }}
                        placeholder="0.00"
                      />
                    </Form.Item>
                  </Col>
                  <Col span={7}>
                    <Form.Item
                      {...restField}
                      label="折扣 (%)"
                      name={[name, 'discount']}
                      rules={[{ required: true, message: '请输入折扣' }]}
                    >
                      <InputNumber
                        min={1}
                        max={100}
                        style={{ width: '100%' }}
                        placeholder="100"
                      />
                    </Form.Item>
                  </Col>
                  <Col span={2} style={{ display: 'flex', alignItems: 'flex-end' }}>
                    {fields.length > 1 && (
                      <Form.Item>
                        <Button
                          type="text"
                          danger
                          icon={<MinusCircleOutlined />}
                          onClick={() => remove(name)}
                        />
                      </Form.Item>
                    )}
                  </Col>
                </Row>
              </Card>
            ))}
            <Form.Item>
              <Button
                type="dashed"
                onClick={() => add({ size: '', price: 0, discount: 100 })}
                block
                icon={<PlusOutlined />}
              >
                添加规格
              </Button>
            </Form.Item>
          </>
        )}
      </Form.List>

      <Divider />

      <Form.Item
        label="菜品图片"
        tooltip="最多上传5张图片，每张不超过5MB"
      >
        <Upload
          listType="picture-card"
          fileList={fileList}
          onChange={handleUploadChange}
          beforeUpload={beforeUpload}
          customRequest={customUpload}
          maxCount={5}
        >
          {fileList.length >= 5 ? null : uploadButton}
        </Upload>
      </Form.Item>

      <Divider />

      <Form.Item>
        <Space>
          <Button
            type="primary"
            htmlType="submit"
            loading={loading}
            icon={<SaveOutlined />}
          >
            {dish ? '保存修改' : '创建菜品'}
          </Button>
          <Button
            onClick={onCancel}
            icon={<CloseOutlined />}
          >
            取消
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );
};

export default DishForm;